package cn.btks.backstagemanage.user.controller;

import cn.btks.backstagemanage.unit.pojo.Unit;
import cn.btks.backstagemanage.user.pojo.User;
import cn.btks.backstagemanage.user.service.UserService;
import cn.btks.commonserver.result.MenuSourceEnum;
import cn.btks.commonserver.result.ResultState;
import cn.btks.commonserver.result.StateInfo;
import cn.btks.commonserver.result.SystemLogEnum;
import cn.btks.commonserver.util.JwtUtil;
import cn.btks.commonserver.valid.SystemLog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Optional;

/**
 * @Author lijun
 * @Date 2021/1/11 18:48
 */
@Slf4j
@RestController
@RequestMapping("api/v1.0/user")
@Api(tags = "用户模块")
@Validated
public class UserController {

    @Autowired
    UserService userService;

    @SystemLog(type = SystemLogEnum.QUERY_LOG, moduleMessage = MenuSourceEnum.MENU_BACKSTAGE)
    @GetMapping("/findById/{id}")
    @ApiOperation("根据ID查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "用户ID", required = true, dataType = "long"),
            @ApiImplicitParam(paramType = "header", name = "token", value = "token密匙", required = true, dataType = "string")
    })
    public ResultState findById(@PathVariable("id") Long id) {
        User user = userService.findById(id);
        return user != null ? new ResultState(StateInfo.FIND_OK.getCode(),
                StateInfo.FIND_OK.getMsg(), user) : new ResultState(StateInfo.FIND_NULL.getCode(),
                StateInfo.FIND_NULL.getMsg());
    }

    @GetMapping("/record/visit/totals")
    @ApiOperation("存储系统登录次数")
    public void loginCount(@RequestParam(value = "userName") String userName,
                           @RequestParam(value = "name") String name) {
        userService.recordLoginCount(userName, name);
    }

    @GetMapping("/record/list")
    @ApiOperation("查询系统登录次数")
    public ResultState getLoginRecord() {
        int num = userService.getLoginRecord();
        return new ResultState<>(StateInfo.FIND_OK.getCode(), StateInfo.FIND_OK.getMsg(), num);
    }

    @SystemLog(type = SystemLogEnum.QUERY_LOG, moduleMessage = MenuSourceEnum.MENU_BACKSTAGE)
    @GetMapping("/findByUserName/{userName}")
    @ApiOperation("根据用户名查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "userName", value = "用户名", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "header", name = "token", value = "token密匙", required = true, dataType = "string")
    })
    public ResultState findByUserName(@PathVariable("userName") String userName) {
        User user = userService.findByUserName(userName);
        return user != null ? new ResultState(StateInfo.FIND_OK.getCode(),
                StateInfo.FIND_OK.getMsg(), user) : new ResultState(StateInfo.FIND_NULL.getCode(),
                StateInfo.FIND_NULL.getMsg());
    }

    @SystemLog(type = SystemLogEnum.QUERY_LOG, moduleMessage = MenuSourceEnum.MENU_BACKSTAGE)
    @GetMapping("/findPages")
    @ApiOperation("分页查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNumber", value = "当前页码", required = true, dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页行数", required = true, dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "userName", value = "用户名（登录用户名）", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "name", value = "人员名称", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "unitId", value = "单位ID", required = false, dataType = "long"),

            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState findPagesByUserNameAndUnitId(Integer pageNumber, Integer pageSize, String userName, String name, Long unitId, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        Optional<Claims> optional = JwtUtil.getClaimsFromToken(token, JwtUtil.jwtsSecret);
        if (optional.isPresent()) {
            Claims claims = optional.get();
            Object obj = claims.get("unit");
            Unit unit = JSONArray.parseObject(JSON.toJSONString(obj), Unit.class);
            if (unit != null) {
                if (unit.getCityCode().equals("65")) {
                    return userService.findPageList(pageNumber, pageSize, userName, name, unitId);
                } else {
                    return userService.findPageList1(pageNumber, pageSize, userName, name, unitId, unit.getCityId());
                }
            }
        }
        return userService.findPageList(pageNumber, pageSize, userName, name, unitId);
    }

    @SystemLog(type = SystemLogEnum.SAVE_LOG, moduleMessage = MenuSourceEnum.MENU_BACKSTAGE)
    @PostMapping("/save")
    @ApiOperation(value = "保存用户信息", notes = "保存用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userName", value = "用户名", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "name", value = "人员名", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "password", value = "密码", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "roles", value = "角色对象列表", required = true, dataType = "list"),
            @ApiImplicitParam(paramType = "query", name = "email", value = "e-mail", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "post", value = "职位", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "unitId", value = "单位ID", required = false, dataType = "long"),

            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState save(@RequestBody User user) throws Exception {
        return userService.save(user);
    }

    @SystemLog(type = SystemLogEnum.UPDATE_LOG, moduleMessage = MenuSourceEnum.MENU_BACKSTAGE)
    @PostMapping("/update")
    @ApiOperation(value = "更新用户信息", notes = "更新用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "用户ID", required = true, dataType = "long"),
            @ApiImplicitParam(paramType = "query", name = "userName", value = "用户名(用户名不允许用户修改)", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "name", value = "人员名", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "password", value = "密码", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "roles", value = "角色对象列表", required = true, dataType = "list"),
            @ApiImplicitParam(paramType = "query", name = "email", value = "e-mail", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "post", value = "职位", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "unitId", value = "单位ID", required = false, dataType = "long"),

            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState update(@RequestBody User user) throws Exception {
        log.info(user.toString());
        return userService.update(user);
    }

    @SystemLog(type = SystemLogEnum.DELETE_LOG, moduleMessage = MenuSourceEnum.MENU_BACKSTAGE)
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除用户信息", notes = "删除用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "用户ID", required = true, dataType = "long"),

            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState delete(@PathVariable("id") Long id) {
        return userService.delete(id);
    }

    @SystemLog(type = SystemLogEnum.DELETE_LOG, moduleMessage = MenuSourceEnum.MENU_BACKSTAGE)
    @DeleteMapping("/deleteConnection/{id}")
    @ApiOperation(value = "删除用户关联角色信息", notes = "删除用户关联角色信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "用户ID", required = true, dataType = "long"),

            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState deleteConnection(@PathVariable("id") Long id) {
        return userService.deleteConnection(id);
    }

    @SystemLog(type = SystemLogEnum.QUERY_LOG, moduleMessage = MenuSourceEnum.MENU_BACKSTAGE)
    @PostMapping("/updatePassword/{oldPassword}/{newPassword}/{id}")
    @ApiOperation("修改用户密码")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "oldPassword", value = "旧密码", required = true, dataType = "long"),
            @ApiImplicitParam(paramType = "path", name = "newPassword", value = "新密码", required = true, dataType = "long"),
            @ApiImplicitParam(paramType = "path", name = "id", value = "用户ID", required = true, dataType = "long"),
            @ApiImplicitParam(paramType = "header", name = "token", value = "token密匙", required = true, dataType = "string")
    })
    public ResultState findById(@PathVariable("oldPassword") String oldPassword, @PathVariable("newPassword") String newPassword, @PathVariable("id") Long id) throws IOException {
        return userService.updatePassword(oldPassword, newPassword, id);
    }
}
